/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package mundialfp.view.pais;

import java.awt.Color;
import java.awt.HeadlessException;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;
import mundialfp.view.ResponseManager;
import mundialfp.view.message.MessageService;
import mundialfp.view.tables.paisABM.PaisABMTableModel;
import mundialfp.view.tables.PaisTableModel;
import mundialfp.view.tables.paisABM.PaisTableSorter;
import mundialfp.view.tables.TableCustom1;
import mundialfp.view.tables.paisABM.TablePaisManager;
import mundialfp.view.tables.TableUtils;
import mundialfp.view.ws.PaisWSService;
import uy.com.pzit.fpmundialmodel.web.ws.Pais;
import uy.com.pzit.fpmundialmodel.web.ws.PaisResponse;
import uy.com.pzit.core.util.ImageUtil;

/**
 *
 * @author pferraz
 */
public class PaisABM extends javax.swing.JFrame {

    private Pais paisTemp;
    private Icon noFoto;
    int BANDERA_HEIGHT = 30;
    int BANDERA_WIDTH = 50;

    private final TablePaisManager tGenerator;
    private final TableCustom1 tblListaPais;
    private final PaisTableSorter paisTableSorter;

    /**
     * Creates new form PaisABM
     */
    public PaisABM() {
        tGenerator = new TablePaisManager();
        paisTableSorter = new PaisTableSorter();
        this.tblListaPais = new TableCustom1(2);
        initComponents();
        formLoad();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pnlPaisABM = new javax.swing.JPanel();
        lblBandera = new javax.swing.JLabel();
        lblNombre = new javax.swing.JLabel();
        btnCancel = new javax.swing.JButton();
        btnSave = new javax.swing.JButton();
        btnImageSelect = new javax.swing.JButton();
        txtNombre = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        pnlListaPais = new javax.swing.JPanel();
        txtPaisQuickSearch = new javax.swing.JTextField();
        btnNuevoPais = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Edición Pais");
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        setName("frmPais"); // NOI18N
        setResizable(false);

        pnlPaisABM.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        lblBandera.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/sinfoto.jpg"))); // NOI18N
        pnlPaisABM.add(lblBandera, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 72, -1, 80));

        lblNombre.setFont(new java.awt.Font("Trebuchet MS", 0, 18)); // NOI18N
        pnlPaisABM.add(lblNombre, new org.netbeans.lib.awtextra.AbsoluteConstraints(381, 185, -1, -1));

        btnCancel.setFont(new java.awt.Font("Trebuchet MS", 0, 11)); // NOI18N
        btnCancel.setText("Cancelar");
        btnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelActionPerformed(evt);
            }
        });
        pnlPaisABM.add(btnCancel, new org.netbeans.lib.awtextra.AbsoluteConstraints(209, 198, -1, -1));

        btnSave.setFont(new java.awt.Font("Trebuchet MS", 0, 11)); // NOI18N
        btnSave.setText("Guardar");
        btnSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSaveActionPerformed(evt);
            }
        });
        pnlPaisABM.add(btnSave, new org.netbeans.lib.awtextra.AbsoluteConstraints(304, 191, -1, 36));

        btnImageSelect.setText("Subir imagen");
        btnImageSelect.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnImageSelectActionPerformed(evt);
            }
        });
        pnlPaisABM.add(btnImageSelect, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 70, -1, -1));

        txtNombre.setFont(new java.awt.Font("Trebuchet MS", 0, 14)); // NOI18N
        txtNombre.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtNombreActionPerformed(evt);
            }
        });
        pnlPaisABM.add(txtNombre, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 11, 237, -1));

        jLabel1.setFont(new java.awt.Font("Trebuchet MS", 0, 14)); // NOI18N
        jLabel1.setText("Nombre");
        pnlPaisABM.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 14, -1, -1));

        txtPaisQuickSearch.setFont(new java.awt.Font("Trebuchet MS", 0, 13)); // NOI18N
        txtPaisQuickSearch.setForeground(java.awt.Color.gray);
        txtPaisQuickSearch.setText("Búsqueda rápida ...");
        txtPaisQuickSearch.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                txtPaisQuickSearchFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtPaisQuickSearchFocusLost(evt);
            }
        });

        javax.swing.GroupLayout pnlListaPaisLayout = new javax.swing.GroupLayout(pnlListaPais);
        pnlListaPais.setLayout(pnlListaPaisLayout);
        pnlListaPaisLayout.setHorizontalGroup(
            pnlListaPaisLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlListaPaisLayout.createSequentialGroup()
                .addComponent(txtPaisQuickSearch, javax.swing.GroupLayout.PREFERRED_SIZE, 234, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 146, Short.MAX_VALUE))
        );
        pnlListaPaisLayout.setVerticalGroup(
            pnlListaPaisLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlListaPaisLayout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(txtPaisQuickSearch, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(453, 453, 453))
        );

        btnNuevoPais.setFont(new java.awt.Font("Trebuchet MS", 1, 14)); // NOI18N
        btnNuevoPais.setText("NUEVO");
        btnNuevoPais.setName(""); // NOI18N
        btnNuevoPais.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNuevoPaisActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addComponent(pnlListaPais, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(7, 7, 7)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(pnlPaisABM, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(3, 3, 3)
                        .addComponent(btnNuevoPais))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(37, 37, 37)
                .addComponent(pnlPaisABM, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(6, 6, 6)
                .addComponent(btnNuevoPais, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addComponent(pnlListaPais, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void txtNombreActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtNombreActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtNombreActionPerformed

    private void btnImageSelectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnImageSelectActionPerformed
        // TODO add your handling code here:
        JFileChooser fileChooser = new JFileChooser();
        try {

            FileNameExtensionFilter filtro = new FileNameExtensionFilter(".jpg & .png", "jpg", "png");
            fileChooser.setFileFilter(filtro);
            fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            int result = fileChooser.showOpenDialog(fileChooser);
            if (result == JFileChooser.APPROVE_OPTION) {

                File file = fileChooser.getSelectedFile();
                String fileName = file.getPath();
                if (file.length() < 100000) {
                    int width = 120;
                    int height = 80;
                    BufferedImage bImage = ImageIO.read(file);
                    Image image = bImage.getScaledInstance(width, height, BufferedImage.SCALE_DEFAULT);
                    ImageIcon icon = new ImageIcon(image);

                    icon.getImage().getScaledInstance(width, height, Image.SCALE_DEFAULT);
                    getPaisTemp().setBanderaB64(ImageUtil.encodeToString(bImage, fileName.substring(fileName.length() - 3)));
                    lblBandera.setIcon(icon);
                } else {
                    MessageService.infoBox("Ingrese una foto con un tamaño máximo de 100 KB", "Excede tamaño de imagen");
                }

            }
        } catch (HeadlessException | IOException e) {
            JOptionPane.showMessageDialog(null, e.getMessage());
        }
    }//GEN-LAST:event_btnImageSelectActionPerformed

    private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed
        getPaisTemp().setNombre(txtNombre.getText());
        Pais p = PaisWSService.addPais(paisTemp);
        addSorterByPaisName(p);
        cleanPais();
        pnlPaisABM.setVisible(false);
    }//GEN-LAST:event_btnSaveActionPerformed

    private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
        // TODO add your handling code here:
        cleanPais();
        pnlPaisABM.setVisible(false);

    }//GEN-LAST:event_btnCancelActionPerformed

    private void btnNuevoPaisActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNuevoPaisActionPerformed
        // TODO add your handling code here:
        pnlPaisABM.setVisible(true);
    }//GEN-LAST:event_btnNuevoPaisActionPerformed

    private void txtPaisQuickSearchFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtPaisQuickSearchFocusGained
        // TODO add your handling code here:
        txtPaisQuickSearch.setText("");
        txtPaisQuickSearch.setForeground(Color.BLACK);
    }//GEN-LAST:event_txtPaisQuickSearchFocusGained

    private void txtPaisQuickSearchFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtPaisQuickSearchFocusLost
        // TODO add your handling code here:
        if (txtPaisQuickSearch.getText().length() == 0) {
            txtPaisQuickSearch.setText("Búsqueda rápida ...");
            txtPaisQuickSearch.setForeground(Color.GRAY);
        }
    }//GEN-LAST:event_txtPaisQuickSearchFocusLost

    private void cleanPais() {
        lblBandera.setIcon(noFoto);
        txtNombre.setText("");
        this.paisTemp = null;
    }

    public Pais getPaisTemp() {
        if (paisTemp == null) {
            paisTemp = new Pais();
        }
        return paisTemp;
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnImageSelect;
    private javax.swing.JButton btnNuevoPais;
    private javax.swing.JButton btnSave;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel lblBandera;
    private javax.swing.JLabel lblNombre;
    private javax.swing.JPanel pnlListaPais;
    private javax.swing.JPanel pnlPaisABM;
    private javax.swing.JTextField txtNombre;
    private javax.swing.JTextField txtPaisQuickSearch;
    // End of variables declaration//GEN-END:variables

    private void formLoad() {

        btnNuevoPais.requestFocus();
        txtPaisQuickSearch.setForeground(Color.GRAY);
        noFoto = lblBandera.getIcon();
        pnlPaisABM.setVisible(false);
        tGenerator.createPaisTable("PaisABM", 234, 447, tblListaPais, pnlListaPais, txtPaisQuickSearch);
        PaisResponse resp = PaisWSService.getPaises();
        if (ResponseManager.validateResponse(resp)) {
            PaisABMTableModel dTM = new PaisABMTableModel(0);
            tblListaPais.setModel(dTM);
            for (Pais p : resp.getPaises()) {
                Object[] newRow = {new ImageIcon(ImageUtil.resizeImage(ImageUtil.decodeToImage(p.getBanderaB64()), BANDERA_WIDTH, BANDERA_HEIGHT)), p.getNombre()};
                dTM.addRow(newRow);
            }

            paisTableSorter.initQuickSearch(tblListaPais, txtPaisQuickSearch, BANDERA_HEIGHT + 5,1);
        }

    }

    private void addSorterByPaisName(Pais p) {
        int indexToInsert = -1;//Lo inicializo en -1 para saber que si queda igual el pais a insertar es el mayor de todos
        String paisEnTabla;
        int rowCount = tblListaPais.getModel().getRowCount();
        Object[] newRow = {new ImageIcon(ImageUtil.resizeImage(ImageUtil.decodeToImage(p.getBanderaB64()), BANDERA_WIDTH, BANDERA_HEIGHT)), p.getNombre()};
        if (rowCount > 0) {
            for (int i = 0; i < rowCount; i++) {
                paisEnTabla = (String) tblListaPais.getModel().getValueAt(i, 1);
                if (paisEnTabla.compareTo(p.getNombre()) > 0) {
                    indexToInsert = i;
                    break;
                }
            }
        }

        if (rowCount == 0 || indexToInsert == -1) {
            ((PaisTableModel) tblListaPais.getModel()).addRow(newRow);
        } else {
            ((PaisTableModel) tblListaPais.getModel()).insertRow(indexToInsert, newRow);
        }

        TableUtils.setHeight(tblListaPais, BANDERA_HEIGHT + 5);
    }

}
